package com.springboot;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wmh
 * @version 1.0 2022/7/3
 * @Description: 统一异常处理
 **/
@ControllerAdvice
public class RoadControllerAdvice {
    /**
     *@Validated 写在方法上的时候会报这个异常
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public String handleEx(BindException e){
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuilder builder = new StringBuilder("RoadControllerAdvice里的：");
        for (FieldError fieldError : fieldErrors) {
            builder.append("属性：").append(fieldError.getField()).append("校验不通过的原因：").append(fieldError.getDefaultMessage()).append(";;");
        }
        return builder.toString();
    }

    /**
     * @Validated 写在类上的时候会报这个异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public List<String> handleEx(ConstraintViolationException e){
        Set<ConstraintViolation<?>> fieldErrors = e.getConstraintViolations();
        StringBuilder builder = new StringBuilder("RoadControllerAdvice里的：");
        List<String> list = fieldErrors.stream().map(v -> "属性：" + v.getPropertyPath() + "，属性值是：" + v.getInvalidValue()
                + "，校验不通过的提示信息：" + v.getMessage()+"，消息模板："+v.getMessageTemplate()).collect(Collectors.toList());
        return list;
    }

    /**
     * 处理所有异常信息
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleEx(Exception e){
        return e.getMessage();
    }
}